﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;

namespace ArgusLib.BugReport.Protocols
{
	public class Mail : IProtocol
	{
		public string SmtpServer { get; set; }
		public int Port { get; set; }
		public MailAddress From { get; set; }
		public IEnumerable<MailAddress> To { get; set; }
		public string Subject { get; set; }
		public string Body { get; set; }
		public NetworkCredential Credentials { get; set; }
		public bool EnableSSL { get; set; }
		
		public Mail(string smtpServer, NetworkCredential credentials, MailAddress from, params MailAddress[] to)
		{
			this.SmtpServer = smtpServer;
			this.Credentials = credentials;
			this.Port = 25;
			this.From = from;
			this.To = to;
			this.Subject = string.Empty;
			this.Body = string.Empty;
			this.EnableSSL = false;
		}

		public bool Send(FileInfo file)
		{
			if (file.Exists == false)
				return false;

			using (MailMessage message = new MailMessage())
			{
				message.From = this.From;
				foreach (MailAddress to in this.To)
					message.To.Add(to);
				message.Subject = this.Subject;
				message.Body = this.Body;
				message.Attachments.Add(new Attachment(file.FullName));
				SmtpClient client = new SmtpClient(this.SmtpServer, this.Port);
				client.Credentials = this.Credentials;
				client.EnableSsl = this.EnableSSL;
				try { client.Send(message); }
				catch (SmtpException) { return false; }
			}
			return true;
		}

		public void SendAsync(FileInfo file, Action<bool> callback)
		{
			ThreadPool.QueueUserWorkItem(new WaitCallback((arg) =>
				{
					bool RetVal = this.Send(file);
					if (callback != null)
						callback(RetVal);
				}));
		}
	}
}
